package com.smart.speaker.controller;

import com.smart.speaker.service.TestService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.concurrent.CompletableFuture;

@RestController
@RequestMapping("/chat")
@CrossOrigin(origins = "*", maxAge = 3600)
@Slf4j
public class ChatController {

    @Autowired
    private TestService testService;

    @PostMapping(value = "init", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter chat(@RequestParam("timestamp") Long timestamp,
                           @RequestParam("audio") MultipartFile audioFile) throws IOException, InterruptedException {

        SseEmitter sseEmitter = new SseEmitter(30000L);
        sseEmitter.send("hello");
        sseEmitter.send(SseEmitter.event()
                .reconnectTime(1000).data("world"));
        sseEmitter.onCompletion(() -> {
            log.info("onCompletion");
        });
        sseEmitter.complete();
        return sseEmitter;
    }

    @GetMapping("test")
    public String test() throws InterruptedException {
        log.info(Thread.currentThread().getName());
        long start = System.currentTimeMillis();
        CompletableFuture<String> future1 = testService.test1();
        CompletableFuture<String> future2 = testService.test2();
        CompletableFuture.allOf(future1, future2).join();
        log.info("cost: {}", System.currentTimeMillis() - start);
        return "test";
    }
}
